<?php
class Astudio {
	public static function main($funcode) {
		sview::verify();
		switch ($funcode) {
			case 1:
				self::__dodetails();
				break;
			case 2:
				self::__doconfig();
				break;
			case 3:
				self::__dogetm3u8();
				break;
			case 4:
				self::__dogetimcond();
				break;
			case 5:
				self::__dosearch();
				break;
			case 6:
				self::__dogetbyids();
				break;
			case 7:
				self::__domain();
				break;
			case 8:
				self::__logcollect();
				break;
			default:
				sview::$view->assign_error(404, lang::text(404));
		}
	}
	
	//直播间检索5-1-5
	private static function __dosearch() {
		$keywords = trim(sview::$ctrl['keywords']);
		$start    = intval(sview::$ctrl['offset']);
		$limit    = intval(sview::$ctrl['limit']);
		if ($limit < 1 || $limit > 30) {
			$limit = 15;
		}
		$nlen     = strlen($keywords);
		if ($nlen < 1 || $nlen > 20) {
			sview::$view->assign_error(506, lang::text(506));
		}
		$list     = array();
		$data     = api_search::start($keywords, 0, $start, $limit);
		if (isset($data['list']) && !empty($data['list'])) {
			foreach ($data['list'] as $item) {
				$list[] = self::get_studio($item['id']);
			}
		}
		sview::$view->assign('datasets', $list);
		sview::$view->display();
	}
	
	//根据id获取主播信息5-1-6
	private static function __dogetbyids() {
		$ids      = trim(sview::$ctrl['ids']);
		$ids      = explode(',', $ids);
		$list     = array();
		$limit    = 30;
		foreach ($ids as $studioid) {
			if (!is_numeric($studioid) || $limit < 0) {
				continue;
			}
			$item   = self::get_studio($studioid);
			if (!$item) {
				continue;
			}
			$limit -= 1;
			$list[] = $item;
		}
		sview::$view->assign('datasets', $list);
		sview::$view->display();
	}
	
	private static function get_studio($id) {
		$uorm   = model::load('live/userinfo');
		$sorm   = model::load('live/studio');
		$aorm   = model::load('live/anchor');
		$sstud  = $sorm->get_one($id);
		if (!$sstud) {
			return false;
		}
		$suser  = $uorm->set_devision($sstud['userid'])->get_one($sstud['userid']);
		$anchor = $aorm->get_one($sstud['userid']);
		$lv     = api_lv::item($suser['lv'], 0);
		$airtime= ($sstud['airtime'] < config::$nowtime)? 0:$sstud['airtime'];
		$tags   = empty($sstud['tags'])? array():json_decode($sstud['tags'], true);
		$viewer = api_notify::oluser($id, $sstud);
		
		$iscurated = api_studio::grade($anchor['starlv'], $sstud['iscurated']);
		$data   = array('userid'=>$sstud['userid'], 'studioid'=>$sstud['id'], 
			'nickname'=>htmlspecialchars_decode($suser['nickname']), 'viewer'=>$viewer,
			'avtar'=>$suser['thumb'], 'title'=>htmlspecialchars_decode($sstud['title']), 'airtime'=>$airtime,
			'thumb'=>$sstud['thumb'], 'xfans'=>$anchor['xfans'], 'olstatus'=>$sstud['olstatus'], 'tags'=>$tags,
			'lvicon'=>$lv['iconsrc'], 'alv'=>$suser['lv'], 'iscurated'=>$iscurated
		);
		return $data;
	}
	
	//获取IM请求的资料信息列表
	private static function __im($userid) {
		list($host, $port) = explode(':', api_rtmpuri::im());
		$ims   = api_rtmpuri::ims();
		$im    = array('host'=>$host, 'port'=>intval($port), 'ims'=>$ims, 'iuin'=>0, 'nick'=>'Anonymous');
		if ($userid > 0) {//处理IM的请求Token
			$user        = model::load('live/userinfo')->set_devision($userid)->get_one($userid);
			$im['iuin']  = $userid;
			$im['nick']  = $user['nickname'];
			$im['token']  = md5('T15R2d'.$user['loginpw'].'3748sf');
			api_im::regtoken($im['iuin'], $im['iuin'], $im['token']);
		} else {
			//php 和 c/c++不一样，这里要注意
			$im['token'] = md5($_SERVER['HTTP_SIGNATURE']);
			$im['iuin']  = api_im::INTBASE + input::strhash($_SERVER['HTTP_SIGNATURE']);
			api_im::regtoken($im['iuin'], 0, $im['token']);
		}
		return $im;
	}
	
	//请求获取直播IM5-1-4
	private static function __dogetimcond() {
		$acl    = acl::getinst('vedio');
		$userid = 0;
		if ($acl->user) {
			$userid  = (int)$acl->user['id'];
		}
		sview::$view->assign('datasets', self::__im($userid));
		sview::$view->display();
	}
	
	//直播间信息5-1-1
	private static function __dodetails() {
		sview::$ctrl['studioid'] = intval(sview::$ctrl['studioid']);
		//判断直播间是否存在 不存在跳转
		$studio = model::load('live/studio')->get_one(sview::$ctrl['studioid']);
		if (!$studio || $studio['status'] != 1) {
			sview::$view->assign_error(80082, lang::text(80082));
		}
		$user   = model::load('live/userinfo')->set_devision($studio['userid'])->get_one($studio['userid']);
		$anchor = model::load('live/anchor')->get_one($studio['userid']);
		$lv    	= api_lv::item($user['lv'], 0);
		$title  = stripslashes($studio['title']);
		$acl    = acl::getinst('vedio');
		$isfans = 0;
		$userid = 0;
		$isfeed = 0;
		$tags   = json_decode($studio['tags'], true);
		$myeventid = 0;
		if ($acl->user) {
			$userid  = (int)$acl->user['id'];
			if ($userid != $studio['userid']) {
				$isfans  = api_stats::hattens($userid, $studio['userid']);
				$feed    = api_studio::feed($userid, $studio['id']);
				$isfeed  = isset($feed[$studio['id']]) ? 1 : 0;
				if ($tags && count($tags) > 0) {
					$studio['tags'] = array();
					foreach ($tags as $item) {
						$studio['tags'][] = $item['name'];
					}
					$studio['tags'] = implode(' ', $studio['tags']);
				}
				api_studio::visit($userid, $studio);
			} 
			//判断当前用户是否已经再直播
			$mystudio = model::load('live/studio')->get_item(array('userid'=>$userid));
			if ($mystudio && $mystudio['olstatus'] == 1 /*&& $studio['oltools'] != 'pc'*/) {
				$myeventid = (int)api_studio::geteid($mystudio['id'], $userid);
			}
		}
		//遍历获取拉流地址
		$evtid  = (int)api_studio::geteid($studio['id'], $studio['userid']);
		$rtmp   = api_rtmp::recv($studio['id'], $evtid);
		$where  = array('userid'=>$studio['userid'], 'origin'=>1, 'status'=>1, 'isdelete'=>0);
		$m3u8   = model::load('live/video')->get_item($where, '*', 'id', orm::DESC);
		$m3u8   = empty($m3u8)? '':$m3u8['src'];
		$starlv = api_studio::grade($anchor['starlv'], $studio['iscurated']);
		$link   = router::get_base_url().router::get_url('live', $studio['studiono']);
		//获取在线用户数量
		$viewer = api_notify::oluser($studio['id'], $studio);
		$sids   = array($studio['id']);
		$res    = api_im::getoluserstat($sids);
		if (!empty($res)) {//通过IM取实时的数据
			$viewer = $res[$studio['id']]['total'] +
				($res[$studio['id']]['normal'] + $res[$studio['id']]['robot']) * 3;
		}
		$data   = array('userid'=>$studio['userid'], 'studioid'=>$studio['id'], 'nickname'=>htmlspecialchars_decode($user['nickname']),
			'avtar'=>$user['thumb'], 'lvicon'=>$lv['iconsrc'], 'thumb'=>$studio['thumb'], 'title'=>$title, 'rtmp'=>$rtmp,
			'viewer'=>$viewer, 'factor'=>4, 'charms'=>$anchor['charms'], 'olstatus'=>$studio['olstatus'], 'link'=>$link,
			'airtime'=>$studio['airtime'], 'neartime'=>$studio['neartime'], 'tags'=>is_array($tags)? $tags:array(), 'eventid'=>$evtid,
			'isfollow'=>$isfans, 'im'=>self::__im($userid), 'm3u8'=>$m3u8, 'isfeed'=>$isfeed, 'iscurated'=>$starlv, 'myeventid'=>$myeventid
		);
		sview::$view->assign('datasets', $data);
		sview::$view->display();
	}
	
	//配置信息5-1-2
	private static function __doconfig() {
		$data   = array('gifts'=>array(), 'lvs'=>array(), 'motor'=>array(), 'guard'=>array());
		//获取礼物信息
		$fields = 'id,dictid as catid, isshow as issell, reglv as lv,name,isguard,iconsrc as icon'.
			',type,appsrc as swf,gifsrc as gif,`desc`,isnew,coinprice as coin';
		$where  = array('status'=>1);
		$list   = model::load('live/gift')->get_only_list(0, -1, $where, $fields, '`rank`', orm::ASC);
		foreach ($list as $item) {
			$item['lv']     = intval($item['lv']);
			$item['isguard']= intval($item['isguard']);
			$item['coin']   = intval($item['coin']);
			$item['issell'] = intval($item['issell']);
			if ($item['catid'] != 1) {
				$item['issell'] = 0;
			}
			unset($item['catid']);
			$data['gifts'][]= $item;
		}
		//获取主播等级配置信息
		$fields = 'lv,reftype,iconsrc as icon,coin as exp';
		$list   = model::load('live/level')->get_only_list(0, -1, array(), $fields);
		foreach ($list as $item) {
			$item['exp']   = intval($item['exp']);
			$data['lvs'][] = $item;
		}
		//增加守护的图标地址
		$list   = model::load('live/guard')->get_only_list(0, -1);
		foreach ($list as $item) {
			$data['guard'][] = array('id'=>$item['id'], 'name'=>$item['name'],
				'level1Price'=>$item['coinprice'], 'icon'=>$item['iconsrc']);
		}
		//新增座驾资料信息
		$fields = 'id,iconsrc as icon,appsrc as swf,name';
		$where  = array('isshow'=>1);
		$list   = model::load('live/motor')->get_only_list(0, -1, $where, $fields);
		foreach ($list as $item) {
			$data['motor'][] = $item;
		}
		sview::$view->assign('datasets', $data);
		sview::$view->display();
	}
	
	//直播间历史回播5-1-3
	private static function __dogetm3u8() {
		$anchorid = intval(sview::$ctrl['anchorid']);
		$start  = intval(sview::$ctrl['offset']);
		$limit  = intval(sview::$ctrl['limit']);
		$where  = array('userid'=>$anchorid, 'origin'=>1, 'status'=>1, 'isdelete'=>0);
		$where[]= array('addtime', strtotime('-3 month'), orm::OP_GE);
		$fields = 'title,thumb,firstpic,src,mins,addtime';
		$vorm   = model::load('live/video');
		$acl    = acl::getinst('vedio');
		$aorm   = model::load('live/anchor');
		if ($acl->user) {
			$userid = $acl->user['id'];
			if ($userid != $anchorid) {
				$anchor = $aorm->get_one($anchorid);
				$limit  = $anchor['starlv'] != 4 ? 3 : 1;
			}
		} else {
			$anchor = $aorm->get_one($anchorid);
			$limit  = $anchor['starlv'] != 4 ? 3 : 1;
		}
		if ($limit < 1 || $limit > 30) {
			$limit = 15;
		}
		$data = $vorm->get_only_list($start, $limit, $where, $fields, 'id', orm::DESC);
		if ($data) {
			foreach ($data as &$item) {
				$item['thumb'] = static_uri().$item['thumb'];
				$item['src']   = static_uri().$item['src'];
				$item['firstpic'] = static_uri().$item['firstpic'];
			}
		}
		sview::$view->assign('datasets', $data);
		sview::$view->display();
	}
	
	//根据标识返回直播间ID和用户ID 5-1-7
	private static function __domain() {
		$sign   = trim(sview::$ctrl['sign']);
		$where  = array('studiono'=>$sign);
		$studio = model::load('live/studio')->get_item($where);
		$data   = array();
		if ($studio && $studio['status']) {
			$data = array('userid'=>$studio['userid'], 'studioid'=>$studio['id']);
		}
		sview::$view->assign('datasets', $data);
		sview::$view->display();
	}
	
	//日志收集 分析进入直播间和离开直播间事件 5-1-8
	private static function __logcollect() {
		sview::$ctrl['isenter']  = intval(sview::$ctrl['isenter']);
		sview::$ctrl['studioid'] = intval(sview::$ctrl['studioid']);
		$acl    = acl::getinst('vedio');
		$userid = 0;
		if ($acl->user) {
			$userid  = (int)$acl->user['id'];
		}
		$agent  = isset($_SERVER['HTTP_USER_AGENT'])? $_SERVER['HTTP_USER_AGENT']:'';
		$agent  = str_replace('-', '', $agent);
		$device = (!isset($_SERVER['HTTP_DEVTOKEN']))? md5($agent):$_SERVER['HTTP_DEVTOKEN'];
		$dtype  = preg_match('/ios/i', $_SERVER['HTTP_USER_AGENT'])? 'ios':'android';
		//记录每一次request unique uuid
		$ckey   = 'web_lg_'.$device;
		$cache  = cache::getinst('redis');
		$el     = '';
		if (sview::$ctrl['isenter']) {
			$el = $device.'*'.randme::rand_str(16);
			$cache->set($ckey, $el);
			api_charms::addviewer(sview::$ctrl['studioid'], $device);
		} else {
			$el = $cache->get($ckey);
			$cache->delete($ckey);
		}
		//uuid存在的时候记录一下
		if ($el) {
			list($msec, $sec) = explode(' ', microtime());
			$ts  	= $sec * 1000 + intval($msec*1000);
			$arr    = array('sid'=>sview::$ctrl['studioid'], 'userid'=>$userid, 'dev'=>$device, 'ts'=>$ts, 
				'ip'=>get_ip(), 'isenter'=>sview::$ctrl['isenter'], 'dtype'=>$dtype, 'ver'=>$agent, 'el'=>$el);
			ob_end_clean();
			$file   = COREDIR.'/cachedir/video_tmp_log.log';
			error_log(json_encode($arr)."\r\n", 3, $file);
		}
		sview::$view->display();
	}
}